import React, { PureComponent } from 'react'
import { connect } from 'dva';
import { Table, Modal, message, Button } from 'antd';
import { setUpPerson } from './service';
import { SearchRow, SearchCol, SearchButton } from '@/styled/form';

let userIdList = [];

export interface IProps {
  dispatch?: Function,
  children?: React.ReactNode,
  loading: boolean,
  buttons?: Array<any>,
  list: {
    data: Array<any>,
    dataCnt: number
  },
  match: object,
  history: Array<any>
}

interface IState {
  current: number
}
const confirm = Modal.confirm;
const ONE_PAGE_SIZE = 10;

@connect(({ patrol_user, loading, menu }) => ({
  list: patrol_user.list || {},
  loading: loading.effects['patrol_user/queryPage'],
  buttons: menu.buttons
}))
class PatrolUser extends PureComponent<IProps, IState> {

  readonly state: IState = {
    current: 1
  };

  queryData(offset = 1, size = ONE_PAGE_SIZE) {
    const { dispatch } = this.props;

    dispatch({
      type: 'patrol_user/queryPage',
      payload: {
        pageNum: offset,
        pageSize: size,
      },
    });
  }

  initCurrent = () => {
    this.setState({
      current: 1
    })
  };

  componentDidMount() {
    this.queryData();
  }

  onSelectChange = (selectedRowKeys, rowData) => {
    userIdList = [];
    rowData.forEach(item => {
      userIdList.push(item.id);
    });
  };

  onShowSizeChange = (current, pageSize) => {
    const { dispatch } = this.props;
    dispatch({ type: `patrol_user/updateCond`, payload: { pageSize } }).then(() => {
      this.initCurrent()
    })
  }

  showConfirm() { // 是否设为巡逻人
    if (userIdList.length === 0) {
      message.warning('请选中一个或多个');
      return;
    }
    let that = this;
    confirm({
      title: '新增巡逻人员',
      content: '确认是否把选中的人员设置为巡逻人？',
      onOk() {
        let tipMsg = message.loading('');
        return setUpPerson({ userIdList }).then(() => {
          tipMsg();
          message.success('操作成功', 1.5);
          setTimeout(() => {
            userIdList = [];
            that.props.history.push('/data/position_patrol_user');
          }, 1.5);
        }, () => {
          tipMsg();
          message.warning('操作失败', 1.5);
        });
      },
      onCancel() { },
      okText: "确认",
      cancelText: "取消"
    });
  }

  render() {
    const { list, buttons = [] } = this.props;
    const { data = [], dataCnt } = list;

    const btnList = {};
    buttons.forEach(item => {
      btnList[item.name] = item.name
    });
    const rowSelection = {
      onChange: this.onSelectChange,
    };

    const ans = data && Array.isArray(data) ? data.map((item, index) => ({
      key: index,
      id: item.id,
      companyId: item.companyId,
      jobNumber: item.jobNumber ? item.jobNumber : ' ',
      loginName: item.loginName,
      realName: item.realName,
      position: item.positionName ? item.positionName : ' ',
      status: item.statusName,
      mobile: item.mobile ? item.mobile : ' ',
      creater: item.creater,
      roleList: item.roleList && Array.isArray(item.roleList) ? (item.roleList.map(it => it.name)).join(' ') : ' ',
      groupList: item.groupList && Array.isArray(item.groupList) ? (item.groupList.map(it => it.name)).join(' ') : ' ',
    })
    ) : [];
    const pagination = {
      total: dataCnt,
      showTotal: (total: number) => `共 ${total} 条`,
      current: this.state.current,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      showSizeChanger: true,
      onChange: (current: number) => {
        this.setState({ current }, () => this.queryData(current));
      },
    };
    const columns = [{
      title: '工号',
      dataIndex: 'jobNumber',
    }, {
      title: '登录名',
      dataIndex: 'loginName',
    }, {
      title: '真实姓名',
      dataIndex: 'realName',
    }, {
      title: '职位',
      dataIndex: 'position',
    }, {
      title: '手机号',
      dataIndex: 'mobile',
    }, {
      title: '用户角色',
      dataIndex: 'roleList'
    }, {
      title: '部门',
      dataIndex: 'groupList',
    }];
    return (
      <div>
        <SearchRow style={{ margin: '20px 30px 0 30px' }}>
          <SearchCol span={24}>
            <SearchRow type="flex" justify="end">
              <SearchButton onClick={() => { this.showConfirm() }} icon="plus" type="primary">
                设置为巡逻人
              </SearchButton>
            </SearchRow>
          </SearchCol>
        </SearchRow>
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={ans}
          bordered
          loading={this.props.loading}
          rowSelection={rowSelection}
        />
        <Button
          icon="rollback"
          style={{ marginLeft: '40px', marginTop: '-50px', float: 'left' }}
          onClick={() => {
            window.history.back();
          }}
        >返回</Button>
      </div>
    );
  }
}

export default PatrolUser;
